package com.springapp.filter;

import com.snowplowanalytics.snowplow.tracker.DevicePlatform;
import com.snowplowanalytics.snowplow.tracker.Subject;
import com.snowplowanalytics.snowplow.tracker.Tracker;
import com.snowplowanalytics.snowplow.tracker.emitter.Emitter;
import com.snowplowanalytics.snowplow.tracker.emitter.RequestCallback;
import com.snowplowanalytics.snowplow.tracker.emitter.SimpleEmitter;
import com.snowplowanalytics.snowplow.tracker.events.PageView;
import com.snowplowanalytics.snowplow.tracker.http.ApacheHttpClientAdapter;
import com.snowplowanalytics.snowplow.tracker.http.HttpClientAdapter;
import com.snowplowanalytics.snowplow.tracker.payload.TrackerPayload;
import org.apache.commons.lang.StringUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * to record all access server user behavior
 * Created by Alan.he on 2016/8/23.
 */
public class UserBehaviorFilter implements Filter {
    transient static final Logger logger = LoggerFactory.getLogger(UserBehaviorFilter.class);
    private Tracker tracker;
    private final int MAX_PER_ROUTE=50;
    private final int THREAD_COUNT_SEND_EVENT=20;
    private String[] ignoreUrl={"/static/"};

    public void init(FilterConfig filterConfig) throws ServletException {
        // Make a new client with custom concurrency rules
        PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
        manager.setDefaultMaxPerRoute(MAX_PER_ROUTE);
        // Make the client
        CloseableHttpClient client = HttpClients.custom()
                .setConnectionManager(manager)
                .build();

        // Build the adapter
        HttpClientAdapter adapter = ApacheHttpClientAdapter.builder()
                .url("https://d2clni3ws0wkls.cloudfront.net")
                .httpClient(client)
                .build();

        //customize emitter
        Emitter emitter = SimpleEmitter.builder()
                .threadCount(THREAD_COUNT_SEND_EVENT)
                .httpClientAdapter(adapter)
                .requestCallback(new RequestCallback() {
                    public void onSuccess(int i) {
                        logger.info("send {} event successfully",i);
                    }

                    public void onFailure(int i, List<TrackerPayload> list) {
                        logger.error("Failure, successCount: " + i + " failedEvent:" + list.toString());
                    }
                }).build();

        //create tracker
        tracker = new Tracker.TrackerBuilder(emitter, "servlet", "zoom")
                .base64(true)
                .platform(DevicePlatform.Web)
                .build();

        String value = filterConfig.getInitParameter("ignoreUrls");
        if(StringUtils.isNotEmpty(value)) {
            ignoreUrl = StringUtils.split(value, ";");
        }
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        Calendar now = Calendar.getInstance();
        Date date = now.getTime();
        if(isTrackerUrl(request.getRequestURI())) {
            logger.debug(request.getRequestURI());
            // get parameter from request..
//            String guid = CookieUtil.getCookieValue((HttpServletRequest) servletRequest, Constants.COOKIE_MARKETING_GUID, null);
//            String language = CookieUtil.getCookieValue((HttpServletRequest) servletRequest, Constants.COOKIE_WEB_LANGUAGE, null);
            String guid = request.getSession().getId();
            String language = "";
            Subject s1 = new Subject.SubjectBuilder().build();
            s1.setUserId(guid);
            s1.setLanguage(language);
            s1.setIpAddress(request.getLocalAddr());
            s1.setUseragent(request.getHeader("User-Agent"));
            s1.setDomainUserId(guid);
            //        s1.setTimezone("");

            StringBuffer sb_full_url = request.getRequestURL();
            if (StringUtils.isNotEmpty(request.getQueryString())) {
                sb_full_url.append("?").append(request.getQueryString());
            }
            String referrer = request.getHeader("referer");
            tracker.track(PageView.builder()
                    .pageUrl(sb_full_url.toString())
                    .pageTitle("title")
                    .referrer(referrer)
                    .timestamp(date.getTime()).subject(s1)
                    .build());
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    private boolean isTrackerUrl(String uri) {
        if (ignoreUrl != null) {
            for (String str : ignoreUrl) {
                if (uri.startsWith(str)) {
                    return false;
                }
            }
        }
        return true;
    }

    public void destroy() {

    }
}




